<template>
  <div class="integration-detail">
    <!-- 基础信息卡片 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>系统基础信息</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="系统名称">{{ systemInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="系统编码">{{ systemInfo.code }}</el-descriptions-item>
        <el-descriptions-item label="集成类型">{{ getTypeLabel(systemInfo.type) }}</el-descriptions-item>
        <el-descriptions-item label="接口地址">{{ systemInfo.url }}</el-descriptions-item>
        <el-descriptions-item label="认证方式">{{ getAuthTypeLabel(systemInfo.authType) }}</el-descriptions-item>
        <el-descriptions-item label="同步周期">{{ systemInfo.syncInterval }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="systemInfo.status === 'enabled' ? 'success' : 'info'">
            {{ systemInfo.status === 'enabled' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ systemInfo.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 同步历史 -->
    <el-card class="history-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>同步历史</span>
          <el-button @click="loadSyncHistory">刷新</el-button>
        </div>
      </template>
      <el-table :data="syncHistory" border v-loading="syncLoading">
        <el-table-column prop="syncTime" label="同步时间" width="180">
          <template #default="{ row }">{{ formatDateTime(row.syncTime) }}</template>
        </el-table-column>
        <el-table-column prop="result" label="结果" width="100">
          <template #default="{ row }">
            <el-tag :type="row.result === 'success' ? 'success' : 'danger'">
              {{ row.result === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时(ms)" width="100" />
        <el-table-column prop="message" label="说明" min-width="200" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="syncPage"
          v-model:page-size="syncPageSize"
          :total="syncTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadSyncHistory"
          @current-change="loadSyncHistory"
        />
      </div>
    </el-card>

    <!-- 调用日志 -->
    <el-card class="log-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>接口调用日志</span>
          <el-input v-model="logSearch" placeholder="搜索日志" style="width: 200px" clearable @clear="loadLogList" />
          <el-button @click="handleExportLogs">导出日志</el-button>
          <el-button @click="loadLogList">刷新</el-button>
        </div>
      </template>
      <el-table :data="logList" border v-loading="logLoading">
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">{{ formatDateTime(row.timestamp) }}</template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLogLevelType(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="模块" width="120" />
        <el-table-column prop="message" label="日志内容" min-width="300" />
        <el-table-column prop="duration" label="耗时(ms)" width="100" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="logPage"
          v-model:page-size="logPageSize"
          :total="logTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadLogList"
          @current-change="loadLogList"
        />
      </div>
    </el-card>

    <!-- 关联告警 -->
    <el-card class="alert-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>关联告警</span>
          <el-button @click="loadAlertList">刷新</el-button>
        </div>
      </template>
      <el-table :data="alertList" border v-loading="alertLoading">
        <el-table-column prop="alertTime" label="告警时间" width="180">
          <template #default="{ row }">{{ formatDateTime(row.alertTime) }}</template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertLevelType(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="message" label="告警内容" min-width="300" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'resolved' ? 'success' : 'danger'">
              {{ row.status === 'resolved' ? '已处理' : '未处理' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="alertPage"
          v-model:page-size="alertPageSize"
          :total="alertTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadAlertList"
          @current-change="loadAlertList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  getSystemList,
  getSystemLogs,
  getSystemMonitorData,
  getAlertList,
  exportSystemLogs
} from '@/api/message'

const route = useRoute()
const router = useRouter()
const systemId = route.query.id

// 基础信息
const systemInfo = reactive({})

// 同步历史
const syncHistory = ref([])
const syncLoading = ref(false)
const syncPage = ref(1)
const syncPageSize = ref(20)
const syncTotal = ref(0)

// 日志
const logList = ref([])
const logLoading = ref(false)
const logPage = ref(1)
const logPageSize = ref(20)
const logTotal = ref(0)
const logSearch = ref('')

// 告警
const alertList = ref([])
const alertLoading = ref(false)
const alertPage = ref(1)
const alertPageSize = ref(20)
const alertTotal = ref(0)

// 加载基础信息
const loadSystemInfo = async () => {
  try {
    const res = await getSystemList({ id: systemId })
    Object.assign(systemInfo, res.data.list?.[0] || {})
  } catch (error) {
    ElMessage.error('加载系统信息失败')
  }
}

// 加载同步历史
const loadSyncHistory = async () => {
  try {
    syncLoading.value = true
    const res = await getSystemMonitorData({
      systemId,
      page: syncPage.value,
      pageSize: syncPageSize.value
    })
    syncHistory.value = res.data.list
    syncTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('加载同步历史失败')
  } finally {
    syncLoading.value = false
  }
}

// 加载日志
const loadLogList = async () => {
  try {
    logLoading.value = true
    const res = await getSystemLogs({
      systemId,
      page: logPage.value,
      pageSize: logPageSize.value,
      search: logSearch.value
    })
    logList.value = res.data.list
    logTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('加载日志失败')
  } finally {
    logLoading.value = false
  }
}

// 导出日志
const handleExportLogs = async () => {
  try {
    const res = await exportSystemLogs({
      systemId,
      search: logSearch.value
    })
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `系统日志_${systemInfo.name || systemId}_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('导出日志失败')
  }
}

// 加载告警
const loadAlertList = async () => {
  try {
    alertLoading.value = true
    const res = await getAlertList({
      systemId,
      page: alertPage.value,
      pageSize: alertPageSize.value
    })
    alertList.value = res.data.list
    alertTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('加载告警失败')
  } finally {
    alertLoading.value = false
  }
}

// 工具方法
const formatDateTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}
const getTypeLabel = (type) => {
  const map = { rest: 'REST API', soap: 'SOAP', db: '数据库', other: '其他' }
  return map[type] || type
}
const getAuthTypeLabel = (authType) => {
  const map = { token: 'Token', basic: 'Basic Auth', oauth2: 'OAuth2', none: '无' }
  return map[authType] || authType
}
const getLogLevelType = (level) => {
  const map = { INFO: 'info', WARN: 'warning', ERROR: 'danger', DEBUG: 'success' }
  return map[level] || 'info'
}
const getAlertLevelType = (level) => {
  const map = { 严重: 'danger', 高: 'warning', 中: 'info', 低: 'success' }
  return map[level] || 'info'
}
const goBack = () => {
  router.back()
}

// 初始化
onMounted(() => {
  loadSystemInfo()
  loadSyncHistory()
  loadLogList()
  loadAlertList()
})
</script>

<style lang="scss" scoped>
.integration-detail {
  padding: 20px;
  .info-card, .history-card, .log-card, .alert-card {
    margin-bottom: 24px;
  }
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 